package blog.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.service.CategoryService;

import blog.entity.Category;
import blog.mapper.ArticleMapper;
import blog.mapper.CategoryMapper;
@Service
public class CategoryServiceImpl implements CategoryService {
	@Autowired
	private CategoryMapper categoryMapper;
	@Autowired
	private ArticleMapper articleMapper;
	
	public List<Category> listCategory() {
		return categoryMapper.listCategory();
	}

	@Override
	public List<Category> listSub(Integer parentCateId) {
		return categoryMapper.listCategoryByParentId(parentCateId);
	}

	@Override
	public List<Category> listCategoryInfo() {
		//先获取所有分类
		List<Category> listCategory = categoryMapper.listCategory();
		//再获取分类对应的文章数量
		for (Category category : listCategory) {
			Integer articleCount = categoryMapper.getArticleCountByCategoryId(category.getCategoryId());
			category.setArticleCount(articleCount);
		}
		return listCategory;
	}

	@Override
	public int addCategory(Category category) {
		return categoryMapper.addCategory(category);
	}

	@Override
	public int deleteCategoryById(Integer categoryId) {
		return categoryMapper.deleteCategoryById(categoryId);
	}

	@Override
	public Category getCategoryById(Integer categoryId) {
		//分类信息
		return categoryMapper.getCategoryById(categoryId);
	}

	@Override
	public int editCategory(Category category) {
		//修改文章
		int result = categoryMapper.editCategory(category);
		//修改分类对应的文章映射
		//步骤： 1。先查询分类对应的文章id
		List<Integer> articleIdList = categoryMapper.getArticleIdList(category.getCategoryId());
		//2。删除原先文章分类映射
		for (Integer articleId : articleIdList) {
			articleMapper.deleteArticleCategory(articleId);
		}
		//3。添加新的文章分类映射
		for (Integer articleId : articleIdList) {
			articleMapper.addArticleCategory(articleId, category.getCategoryId());
			articleMapper.addArticleCategory(articleId, category.getCategoryPid());
		}
		return result;
	}

	@Override
	public int getCategoryCount(Integer categoryId) {
		return categoryMapper.getCategoryCount(categoryId);
	}

}
